/**
 * @author  weigao<weigao@iflytek.com>
 *
 * @version 1.0.0
 */
package com.iflytek.uoamp.agent.monitor.dump.obj;

import com.iflytek.uoamp.agent.common.util.HttpHelper;
import com.iflytek.uoamp.agent.common.util.ReadFile;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentConfig;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class FileUpload {

	public static final int NO_FILE = 1;
	public static final int NO_URL = 2;
	public static final int MAX_RETRY = 3;
	public static final int LOAD_FINISH = 0;

	private String fileName;
	private String path;
	private int index = 0;
	private int buffSize = 1024*100;
	private HttpHelper helper = new HttpHelper();
	private static String uploadURL = null;
	private static String upRequestURL = null;

	static {
		String temp = MCAgentConfig.getInstance().getUpload_url();
		if (StringUtils.isNotEmpty(temp)) {
			uploadURL = temp + "/dump/uploadFile";
			upRequestURL = temp + "/dump/getFileLen";
		}
	}

	public FileUpload(String fileName,String path){
		try {
			this.fileName = URLEncoder.encode(URLEncoder.encode(fileName,"utf-8"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			this.fileName = fileName;
		}
		this.path = path;
	}
	
	/**
	 * 上传文件；请求的URL中包括文件名称及文件的开始位置；
	 * 文件的开始位置是为了防止调用远程getFileLen()失败时两端的file len不一致问题
	 */
	private void upload() {
		byte[] tempBytes = ReadFile.read4Byte(path, index, buffSize);
		StringBuffer buffer = new StringBuffer();

		String url = uploadURL+"?file="+fileName+"&index="+index;
		helper.post(url,tempBytes,buffer,"utf-8",1000*10);
	}

	/***
	 * 获取文件的地址；
	 */
	private void getFileLen(){
		StringBuffer buffer = new StringBuffer();
		String url = upRequestURL+"?file="+fileName;
		helper.post(url,new byte[]{},buffer,"utf-8",1000*10);
		this.index = Integer.parseInt(buffer.toString());
	}

	/***
	 * 上传文件；直到文件上传成功；非独立线程，可以因上级线程终止而终止；
	 * @return
	 */
	public int doUpload(){
		File tempFile = new File(path);
		if(!tempFile.exists()){
			Logger.getRootLogger().warn("WARN|try upload file and file is not exits :" + path);
			return NO_FILE;
		}
		if(StringUtils.isEmpty(uploadURL) || StringUtils.isEmpty(upRequestURL)){
			Logger.getRootLogger().warn("WARN|upload url is not config!");
			return NO_URL;
		}
		int tryTime = 0;
		while(true){
			try{
				upload();
				getFileLen();
				if(index>=tempFile.length()){
					break;
				}
			}catch (Exception e){
				Logger.getRootLogger().warn("ERROR| Request time out ",e);
				tryTime++;
			}finally {
				if(tryTime>=5){
					Logger.getRootLogger().warn("WARN|upload retry time is max ");
					break;
				}
			}
		}
		if(tryTime>=5){
			return MAX_RETRY;
		}
		return LOAD_FINISH;
	}

}
